import { connect, useDispatch } from "react-redux";

import { add, jian, asyncAdd } from "./store/actions";

function Hello() {
  const dispatch = useDispatch();

  return (
    <div>
      <h4>Hello</h4>
      <button
        onClick={() => {
          dispatch((dispatch, getState) => {
            console.log("异步动作");
            console.log("dispatch", dispatch);
            console.log("getState", getState);
          });
        }}
      >
        点我, 派发一个异步动作
      </button>

      <button
        onClick={() => {
          dispatch((dispatch) => {
            setTimeout(() => {
              // 派发普通动作
              dispatch({ type: "INCREMENT" });
            }, 1000);
          });
        }}
      >
        延迟1000ms之后自增
      </button>
    </div>
  );
}

function App({ count, add, jian, asyncAdd }) {
  return (
    <div>
      <h1>App</h1>
      <p>COUNT: {count}</p>

      <button onClick={() => add()}>自增</button>
      <button onClick={() => jian()}>自减</button>

      <button
        onClick={() => {
          // 1. 组件上做完异步逻辑之后，再派发动作
          // setTimeout(() => {
          //   add();
          // }, 1000);

          // 2. 组件上只管派发动作
          //    asyncAdd 调用之后，会自动派发 asyncAdd 内返回的动作
          asyncAdd();
        }}
      >
        延迟1000ms之后自增
      </button>

      <hr />

      <Hello />
    </div>
  );
}

export default connect(
  (state) => ({
    count: state.count,
  }),
  {
    add,
    jian,
    asyncAdd,
  }
)(App);
